using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ResourceBlender_Express.Properties;
using System.ComponentModel;

namespace ResourceBlender_Express {
    /// <summary>
    /// A window for changing application settings
    /// </summary>
    public partial class WinOptions : Window {
        /// <summary>
        /// Initializes a new <see cref="WinOptions"/>.
        /// </summary>
        public WinOptions() {
            InitializeComponent();    
        }
        /// <summary>
        /// Validates user input then returns a DialogResult of true.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        public void btnSave_Click(object sender, RoutedEventArgs e) {
            if(databaseSelector.ValidateSettings()) {
                WinProgress dlg = new WinProgress("Checking database connection...", true);
                dlg.Owner = this;
                BackgroundWorker worker = new BackgroundWorker();
                bool canConnect = false;
                worker.DoWork += (s, dwe) => {
                    try {
                        Database db = new Database();
                        db.OpenConnection();
                        db.CloseConnection();
                        canConnect = true;
                        Settings.Default.Save();
                    } catch(Exception ex) {
                        dwe.Result = ex.Message;
                    }
                };
                worker.RunWorkerCompleted += (s, rwe) => {
                    dlg.Close();
                    if(canConnect) {
                        this.DialogResult = true;
                        this.Close();
                    } else {
                        DialogBox.ShowAlert(this, "Could not connect to the database:" + (rwe.Result ?? string.Empty).ToString(), "Error");
                    }
                };
                dlg.Owner = this;
                dlg.Show();
                worker.RunWorkerAsync();
            }
        }
    }
}
